package com.data2wisdom.comm.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
 * 缓存类，能够被spring上下文管理
 * @author LUOWEN
 *
 */
//@EnableCaching
@Configuration
@Component(value="cacheUtil")
public class CacheUtil<T> {
	
	@Value("${cacheType}")
	private  String   cacheType;
	
	private static final String DEFAULT_CACHE = "map";

	@Autowired
	private RedisUtil<T> redisUtil;
	
	
	//private static final String CACHE_KEY = "kafakLogCache";
	
	private Map<String,Map<String ,T>>  cacheMap ;// =  new ConcurrentHashMap<String,String>();
	
	/**
	 * 获得一个Cache，没有则创建一个。
	 * @param cacheName
	 * @return
	 */

	private Map<String ,T> getCacheMap(String key) {
		if( cacheMap == null) {
			cacheMap = new ConcurrentHashMap<>() ;
		}
		if(cacheMap.get(key) == null) {
			Map<String, T> map =  new HashMap<>();
			cacheMap.put(key, map );
		}
		return cacheMap.get(key);
	}
	
	
	
	
	/**
	 * 放入一个map
	 * @param map
	 */
	public  void hset(String key,Map<String ,T> map){
		if(cacheType == null ) {
			cacheType = DEFAULT_CACHE;
			//throw new RuntimeException("CacheUtil.cacheType 的配置有问题,请检查~~");
		}
		if(StringUtils.equals(cacheType, "redis")) {
			redisUtil.hmset(key,map);
		}else {
			getCacheMap(key).putAll(map);
		}
	}
	/**
	 * 获取当前缓存的所有数据
	 * @return
	 */
	public Map<String,T> hget(String key){
		Map<String ,T> hmget = null;
		if(cacheType == null ) {
			cacheType = DEFAULT_CACHE;
			//throw new RuntimeException("CacheUtil.cacheType 的配置有问题,请检查~~");
		}
		if(StringUtils.equals(cacheType, "redis")){
			 hmget = redisUtil.hmget(key);
		}else {
			hmget = getCacheMap(key); 
		}
		return hmget;
	}
	/**
	 * map.key 获取 map.value
	 * @param hashKey  map 键
	 * @return
	 */
	public T hget(String key,String hashKey){
		T value = null;
		if(cacheType == null ) {
			cacheType = DEFAULT_CACHE;
			//throw new RuntimeException("CacheUtil.cacheType 的配置有问题,请检查~~");
		}
		if(StringUtils.equals(cacheType, "redis")){
			value = redisUtil.hmget(key, hashKey);
		}else {
			value = getCacheMap(key).get(hashKey); 
			  
		}
		return value;
	}
	
	
}	
